//
//  KKImageLibrary.m
//  KKImagePickerController
//
//  Created by Mac mini on 16/1/21.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImageLibraryManager.h"

#import "KKImagePickerManager+Tools.h"

@interface KKImageLibraryManager() {
    
    NSMutableArray *_groupItemArray;
    NSMutableArray *_assetItemArray;
}

@end

@implementation KKImageLibraryManager

+ (instancetype)kk_defaultManager {
    
    static KKImageLibraryManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKImageLibraryManager new];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _groupItemArray = [NSMutableArray array];
        _assetItemArray = [NSMutableArray array];
    }
    return self;
}

#pragma mark - Private methods

#pragma mark - Public methods
- (void)kk_searchAllGroupsFromLibrary:(KKImageLibraryManagerAllGroupsHandle)handle {
    
    [_groupItemArray removeAllObjects];
    __weak NSMutableArray* weakGroupArray = _groupItemArray;
    
    {
        // 获取相机相册
        {
            PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
            NSInteger count = smartAlbums.count;
            for (NSInteger index = 0; index < count; index++) {
                PHAssetCollection *assetCollection = [smartAlbums objectAtIndex: index];
                PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
                if (assets.count == 0) {
                    break;
                }
                KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetCollection: assetCollection withItemCounts: assets.count];
                [weakGroupArray insertObject: item atIndex: 0];
            }
        }
        
        {
            //  用户创建的相册
            PHFetchResult *userCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
            NSInteger count = userCollections.count;
            for (NSInteger index = 0; index < count; index++) {
                PHAssetCollection *assetCollection = [userCollections objectAtIndex: index];
                PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
                if (assets.count == 0) {
                    break;
                }
                KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetCollection: assetCollection withItemCounts: assets.count];
                [weakGroupArray addObject: item];
            }
        }
        
        if (handle) {
            handle(weakGroupArray);
        }
        
        // 获取所有资源的集合，并按资源的创建时间排序
//        PHFetchOptions *options = [[PHFetchOptions alloc] init];
//        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
//        {
//            PHFetchResult *momentRes = [PHAssetCollection fetchMomentsWithOptions:options];
//            NSLog(@"momentRes = %@", momentRes);
//        }
        
//        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        
//        PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
//        NSLog(@"assetsFetchResults = %@", assetsFetchResults);
//        // 在资源的集合中获取第一个集合，并获取其中的图片
//        PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
//        PHAsset *asset = assetsFetchResults[0];
//        [imageManager requestImageForAsset:asset
//                                targetSize: CGSizeMake(100, 100)
//                               contentMode:PHImageContentModeAspectFill
//                                   options:nil
//                             resultHandler:^(UIImage *result, NSDictionary *info) {
//                                 
//                                 // 得到一张 UIImage，展示到界面上
//                                 NSLog(@"result = %@", result);
//                             }];
    }
}

//  获取相册中的相片集
- (void)kk_searchAllItemsFromLibraryWithGroup:(id)group result:(KKImageLibraryManagerAllItemsOfGroupHandle)handle {
    
    [_assetItemArray removeAllObjects];
    __weak NSMutableArray* weakAssetItems = _assetItemArray;
    
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:group options:nil];
    for (PHAsset *asset in assets) {
        KKImageItem *item = [KKImageItem new];
        item.asset_8 = asset;
        [weakAssetItems addObject: item];
    }
    if (handle) {
        handle(weakAssetItems);
    }
}

@end



@implementation KKImageLibraryGroupItem

- (instancetype)initWithAssetCollection:(PHAssetCollection *)assetCollection withItemCounts:(NSInteger)counts {
    self = [super init];
    if (self) {
        _kk_assetCollection = assetCollection;
        _kk_groupName = _kk_assetCollection.localizedTitle;
        _kk_count = counts;
    }
    return self;
}

@end

@implementation KKImageItem
@end
